package com.tonysong.oa.yeboa12.config.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tonysong.oa.yeboa12.mapper.AdminMapper;
import com.tonysong.oa.yeboa12.pojo.Admin;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Security;
import java.util.Objects;

@Component //注入到Spring容器中，让其它对象进行调用
public class LoginService implements UserDetailsService {

    @Resource
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //一个方法返回值是个接口：意味返回该接口的一个实现（多态）
        System.out.println("-------------进入了LoginService--------》");
        Admin admin= this.adminMapper.selectOne(new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, username));
        //SpringSecurity会进行密码的认证操作
        if(Objects.isNull(admin)){
             throw new UsernameNotFoundException("错误的账号或密码，登录失败！");
        }

        //获取该用户的角色集合
          admin.setRoles(this.adminMapper.findRoles(admin.getId()));
        return  admin;
    }
}
